﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using MySql.Data.MySqlClient;
using System.Data.SqlClient;

namespace DMU.Gui
{
    public partial class ucLoaiDT : DevExpress.XtraEditors.XtraUserControl
    {
        public ucLoaiDT()
        {
            InitializeComponent();
        }
        
        public static DataTable dtLoaiDT;
        private bool ktThem=true;

        help hp = new help();
        Service sv = new Service();
        
        
        private void gridView1_CustomUnboundColumnData(object sender, DevExpress.XtraGrid.Views.Base.CustomColumnDataEventArgs e)
        {
            if (e.IsGetData)
                e.Value = e.ListSourceRowIndex + 1;
        }
        #region import to mysql

        private void cbbPath_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            string path = hp.openFile();
            if (path != "")
            {
                try
                {
                    cbbPath.Text = path;
                    cbbSheetName.Properties.Items.Clear();
                    cbbSheetName.Properties.Items.AddRange(sv.getEcelSheetName(path));
                    cbbSheetName.Focus();
                }
                catch (Exception et) { hp.showMes("Lỗi khi load sheetName. Vui lòng thử lại ! " + et.Message, 1); }
            }
        }

        private void btnHoanTat_Click(object sender, EventArgs e)
        {
            if (!dxValidationProvider2.Validate())
            {
                if (cbbPath.Text == "")
                {
                    cbbPath.Focus(); return;
                }
                if (cbbSheetName.Text == "")
                {
                    cbbSheetName.Focus(); return;
                }
            }
            DataTable dt=sv.excelToDatatable(cbbPath.Text, "select MaLoaiDT,LoaiDT,GhiChu from [" + cbbSheetName.Text+"]");

            DataColumn cl = new DataColumn("IsActive", Type.GetType("System.Boolean"));
            dt.Columns.Add(cl);

            int rowB = dt.Rows.Count; int d = 0;
            if (rowB > 0)
            {
                try
                {
                    sv.openConnect();
                    foreach (DataRow row in dt.Rows)
                    {
                        if (row["MaLoaiDT"] != null && row["MaLoaiDT"].ToString() != "" && row["LoaiDT"] != null && row["LoaiDT"].ToString() != "")
                        {
                            if (sv.cusTomExecuteNonqueryStore("dmu_proDTThem1", getpara(row["MaLoaiDT"].ToString(), row["LoaiDT"].ToString(), row["GhiChu"].ToString(), true)))
                            {
                                row["IsActive"] = true;
                                d++;
                                try
                                {
                                    dtLoaiDT.ImportRow(row);
                                }
                                catch (Exception) { continue; }

                            }
                        }
                    }
                    sv.closeConnect();
                    dt.Dispose();

                    gridControl1.DataSource = dtLoaiDT;
                    hp.showMes("Import thành công " + dtLoaiDT.Rows.Count + "/" + rowB, -1);
                }
                catch (Exception et)
                {
                    hp.showMes("Import dữ liệu không thành công ! " + et.Message, 1);
                }
            }
            else
                hp.showMes("Dữ liệu trống ! Kiểm tra lại file ", -1);
        }
        #endregion

        private SqlParameter[] getpara(string ma,string ten,string ghiChu,bool active)
        {
            SqlParameter[] pr = new SqlParameter[5];
            pr[0] = new SqlParameter("MaLoaiDT0", ma);
            pr[1] = new SqlParameter("LoaiDT0", ten);
            pr[2] = new SqlParameter("GhiChu0",ghiChu);
            pr[3] = new SqlParameter("IsActive0", active);
            pr[4] = new SqlParameter("MaTruong0", Service.info[4]);
            return pr;
        }

        private string[] getInfo()
        {
            string[] st = new string[4];
            st[0] = txtMa.Text;
            st[1] = txtTen.Text;
            st[2] = txtGhiChu.Text;
            st[3] = chkActive.Checked.ToString();
            return st;
        }

        private void btnLuu_Click(object sender, EventArgs e)
        {
            if (!dxValidationProvider1.Validate())
            {
                if (txtMa.Text == "")
                {
                    txtMa.Focus(); return;
                }
                if (txtTen.Text == "")
                {
                    txtTen.Focus(); return;
                }
            }

            try
            {
                if (ktThem)
                {
                    if (sv.executeScalarStore("dmu_proDTThem", getpara(txtMa.Text, txtTen.Text, txtGhiChu.Text, chkActive.Checked)) == "1")
                        sv.addRow(dtLoaiDT, getInfo());
                    else
                        hp.showMes("Mã ngành đã tồn tại ! ", 1);
                }
                else
                {
                    if (sv.executeNonqueryStore("dmu_proDTSuu", getpara(txtMa.Text, txtTen.Text, txtGhiChu.Text, chkActive.Checked)))
                    {
                        sv.updateRow(dtLoaiDT.Rows[this.BindingContext[dtLoaiDT].Position], getInfo());
                        hp.showMes("Thao tác thành công !", -1);
                    }

                    else
                        hp.showMes("Thao tác không thành công !. Kiểm tra lại dữ liệu", -1);
                }
            }
            catch (Exception et)
            {
                hp.showMes("Thao tác không thành công !. Kiểm tra lại dữ liệu " + et.Message, 1);
            }
        }


        private void chkThem_CheckedChanged(object sender, EventArgs e)
        {
            if (chkThem.Checked)
            {
                txtMa.Focus(); ktThem = true;
                txtMa.Properties.ReadOnly = false;
            }
            else
            {
                ktThem = false;
                txtMa.Properties.ReadOnly = true;
                clickGrid();
                txtTen.Focus();
            }
        }

        private void ucLoaiDT_Load(object sender, EventArgs e)
        {
            DataColumn[] cl = new DataColumn[5];

            cl[0] = new DataColumn("MaLoaiDT", Type.GetType("System.String"));
            cl[1] = new DataColumn("LoaiDT", Type.GetType("System.String"));
            cl[2] = new DataColumn("GhiChu", Type.GetType("System.String"));
            cl[3] = new DataColumn("IsActive", Type.GetType("System.Boolean"));
            dtLoaiDT = new DataTable();
            dtLoaiDT.Columns.AddRange(cl);
            gridControl1.DataSource = dtLoaiDT;
        }

        #region Sự kiện khi clijck vào griview 
        private void clickGrid()
        {
            int d = gridView1.FocusedRowHandle;
            if (d >= 0 && !ktThem)
            {
                txtMa.Text = gridView1.GetRowCellValue(d, "MaLoaiDT").ToString();
                txtTen.Text = gridView1.GetRowCellValue(d, "LoaiDT").ToString();
                txtGhiChu.Text = gridView1.GetRowCellValue(d, "GhiChu").ToString();
                chkActive.Checked = bool.Parse(gridView1.GetRowCellValue(d, "IsActive").ToString());
                txtTen.Focus();
            }
            else
            {
                txtMa.Text = txtTen.Text = txtGhiChu.Text = "";
            }
        }

        #endregion

        private void gridView1_RowCellClick(object sender, DevExpress.XtraGrid.Views.Grid.RowCellClickEventArgs e)
        {
            if (!ktThem)
            {
                clickGrid();

            }
        }

        private void loadDữLiệuToolStripMenuItem_Click(object sender, EventArgs e)
        {
            dtLoaiDT = sv.getDatatable("dmu_proDTLoad", null);
            gridControl1.DataSource = dtLoaiDT;
        }

        private void btnXoaNganh_Click(object sender, EventArgs e)
        {
            int[] a = gridView1.GetSelectedRows();
            if (a.Length > 0)
            {
                if (hp.showMes(a.Length + " đối tượng sẽ bị xóa ?", 2) == DialogResult.Yes)
                {
                    sv.openConnect();
                    int d = 0;
                    for (int i = 0; i < a.Length; i++)
                    {
                        if (gridView1.GetRowCellValue(a[i], "MaLoaiDT") != null)
                        {
                            if (sv.cusTomExecuteScalarStore("dmu_proDTXoa", new SqlParameter("MaLoaiDT0", gridView1.GetRowCellValue(a[i], "MaLoaiDT").ToString()))!="1")
                            { gridView1.UnselectRow(a[i]); d++; }
                        }
                    }
                    gridView1.DeleteSelectedRows();
                    sv.closeConnect();

                    if (d > 0)
                        hp.showMes(d + " đối tượng không thể xóa. Vì nó đang được tham chiếu.", -1);
                }
            }
            else
                hp.showMes("Chọn dòng để thực hiện chức năng này !", -1);
        }

        private void sữuChữaToolStripMenuItem_Click(object sender, EventArgs e)
        {
            chkSuu.Checked = true;
        }

        private void gridControl1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Delete)
            {
                EventArgs et = new EventArgs();
                btnXoaNganh_Click(sender, e);
            }
        }

        private void gridView1_RowClick(object sender, DevExpress.XtraGrid.Views.Grid.RowClickEventArgs e)
        {
            clickGrid();
        }

    }
}
